package com.haiyou.crawler.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author chenzeke
 * @date 2019/9/5 17:15
 */
@Slf4j
public class ImageUtil {

    /**
     * 获取图片验证码
     *
     * @param in
     * @return
     */
    public static String getImageCode(InputStream in) {
        String result = "";
        String BOUNDARY = "---------------------------68163001211748";
        String str = "http://v1-http-api.jsdama.com/api.php?mod=php&act=upload";
        Map<String, String> paramMap = getParamMap();
        try {
            URL url = new URL(str);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + BOUNDARY);
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);

            OutputStream out = new DataOutputStream(connection.getOutputStream());
            // 普通参数
            out(BOUNDARY, paramMap, out);

            // 图片文件
            //这里看情况设置
            String contentType = "image/jpg";
            StringBuffer strBuf = new StringBuffer();
            strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
            strBuf.append("Content-Disposition: form-data; name=\"" + "upload" + "\"; filename=\"" + System.currentTimeMillis() + "\"\r\n");
            strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
            out.write(strBuf.toString().getBytes());
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();

            //读取URLConnection的响应
            InputStream in2 = connection.getInputStream();
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            while (true) {
                int rc = in2.read(buf);
                if (rc <= 0) {
                    break;
                } else {
                    bout.write(buf, 0, rc);
                }
            }
            in2.close();
            //结果输出
            String jsonStr = new String(bout.toByteArray());
            log.info("jsonStr==>" + jsonStr);
            JSONObject json = JSON.parseObject(jsonStr);
            result = json.getJSONObject("data").getString("val");
            if (StringUtils.isBlank(result) || result.length() < 5) {
                log.error("校验失败，图片长度===>" + result.length() + ",result=" + result + ",返回数据为==>" + jsonStr);
                return null;
            } else {
                log.info("验证码识别成功===>" + result);
            }
        } catch (Exception e) {
            log.error("解释图片失败=================>" + e.getMessage(), e);
        }
        return result;
    }

    private static void out(String BOUNDARY, Map<String, String> paramMap, OutputStream out) throws IOException {
        if (paramMap != null) {
            StringBuffer strBuf = new StringBuffer();
            Iterator<Map.Entry<String, String>> iter = paramMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<String, String> entry = iter.next();
                String inputName = entry.getKey();
                String inputValue = entry.getValue();
                strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
                strBuf.append(inputValue);
            }
            out.write(strBuf.toString().getBytes());
        }
    }

    /**
     * 参数信息
     *
     * @return
     */
    private static Map<String, String> getParamMap() {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("user_name", "lenjacn");
        paramMap.put("user_pw", "7ujm8iK,");
        paramMap.put("yzm_minlen", "5");
        paramMap.put("yzm_maxlen", "6");
        return paramMap;
    }

    private static void test() {
        //boundary就是request头和上传文件内容的分隔符
        String BOUNDARY = "---------------------------68163001211748";
        String str = "http://v1-http-api.jsdama.com/api.php?mod=php&act=upload";
        //本地验证码图片路径
        String filePath = "C:/Users/Administrator/Desktop/test2.jpg";
        Map<String, String> paramMap = getParamMap();
        try {
            URL url = new URL(str);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + BOUNDARY);
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);

            OutputStream out = new DataOutputStream(connection.getOutputStream());
            // 普通参数
            out(BOUNDARY, paramMap, out);

            // 图片文件
            if (filePath != null) {
                File file = new File(filePath);
                String filename = file.getName();
                //这里看情况设置
                String contentType = "image/jpeg";
                StringBuffer strBuf = new StringBuffer();
                strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                strBuf.append("Content-Disposition: form-data; name=\"" + "upload" + "\"; filename=\"" + filename + "\"\r\n");
                strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                out.write(strBuf.toString().getBytes());
                DataInputStream in = new DataInputStream(new FileInputStream(file));
                int bytes = 0;
                byte[] bufferOut = new byte[1024];
                while ((bytes = in.read(bufferOut)) != -1) {
                    out.write(bufferOut, 0, bytes);
                }
                in.close();
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();

            //读取URLConnection的响应
            InputStream in = connection.getInputStream();
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            while (true) {
                int rc = in.read(buf);
                if (rc <= 0) {
                    break;
                } else {
                    bout.write(buf, 0, rc);
                }
            }
            in.close();
            //结果输出
            System.out.println(new String(bout.toByteArray()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
